package tokenizer_http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.Buffer;

import tokenizer.Tokenizer;

public class HttpTokenizer<T> implements Tokenizer<T> {
	InputStreamReader inputStreamReader;
	BufferedReader bufferReader;
	String currentLine;
	
	public HttpTokenizer() {
		this.inputStreamReader = null;
		this.bufferReader = null;
		this.currentLine = "";
		
	}
	
	public T nextMessage() {
		StringBuilder message = new StringBuilder("");
		try {
			currentLine = bufferReader.readLine();
		} catch (IOException e) {
			System.out.println("Invalid message/bufferReader problem");
			e.printStackTrace();
		}
		while(isAlive())
		{
			message.append(currentLine);
			System.out.println(message.toString());
			
			try {
				currentLine = bufferReader.readLine();
			} catch (IOException e) {
				System.out.println("Invlaid message/bufferReader problem");
				e.printStackTrace();
			}
				
		}
		if(message.toString().contains("POST"))
			return (T) new PostMessage(message.toString());
		else if(message.toString().contains("GET"))
			return (T) new GetMessage(message.toString());
		
		return null;
		}

	public boolean isAlive() {
		if (currentLine.equals("$"))
			return false;
		return true;
	}

	@Override
	public void addInputStream(InputStreamReader inputStreamReader) {
		this.inputStreamReader = inputStreamReader;
		this.bufferReader = new BufferedReader(inputStreamReader);
	}

}
